#! /usr/bin/env python3
# -*- coding -*-

import unit_strategy
import param_cache
import os
import logging
from aiocoap import *
import asyncio
import json
import common

logging.basicConfig(level=logging.DEBUG)


class UnitCoapProcess(unit_strategy.UnitObject):

    def process1(self, paramc: param_cache.ParamCache):
        self.dest = paramc.get_param_coap_com()['destination']
        self.config_reload_coap(paramc.get_param_config())
        save_info = paramc.get_save_info()
        self.payload = common.ModifyJSON(self.payload, **save_info)
        uri = self.dest + self.url
        coap_types = {'POST': Code.POST, 'GET': Code.GET, 'PUT': Code.PUT}
        payload = self.payload.encode('utf-8')
        coap_type = coap_types[self.type.upper()]
        logging.info("coap info :")
        logging.info(payload)
        logging.info(uri)
        logging.info(coap_type)
        asyncio.get_event_loop().run_until_complete(
            self.coap_send(coap_type, payload, uri)
        )

    def config_reload_coap(self, con):
        self.payload = con['payload']
        self.type = con['type']
        self.url = con['url']
        self.comparison = con['comparison']

    async def coap_send(self, code, payload, uri):
        context = await Context.create_client_context()
        await asyncio.sleep(2)
        request = Message(code=code, uri=uri, payload=payload)
        response = await context.request(request).response
        logging.info('Result: %s \n %r' % (response.code, response.payload))
        result = response.payload.decode('ascii')
        if not self.json_check(result):
            raise RuntimeError

    def json_check(self, json_str):
        data1 = json.loads(json_str)
        data2 = json.loads(self.comparison)
        logging.info(data1, data2)
        if sorted(data1) != sorted(data2):
            return False
        for key, value in data2.items():
            if value == '##NOCHECK':
                continue

            if data1[key] != value:
                return False
        return True


if __name__ == '__main__':
    data1 = r'{"name":"BeJson","url":"http://www.bejson.com","page":88,"isNonProfit":true}'
    data2 = r'{"url":"http://www.bejson.com","name":"BeJson","page":88,"isNonProfit":true}'
    json1 = json.loads(data1)
    json2 = json.loads(data2)
    if sorted(json1) != sorted(json2):
        print("failed")
    for key, value in json2.items():
        if value == '##NOCHECK':
            continue

        if json1[key] != value:
            print("value failed ")

    print("success")
